package com.lxyk.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.lxyk.yygh.common.exception.YyghException;
import com.lxyk.yygh.common.result.ResultCodeEnum;
import com.lxyk.yygh.hosp.repository.ScheduleRepository;
import com.lxyk.yygh.hosp.service.DepartmentService;
import com.lxyk.yygh.hosp.service.HospitalService;
import com.lxyk.yygh.hosp.service.ScheduleService;
import com.lxyk.yygh.model.hosp.BookingRule;
import com.lxyk.yygh.model.hosp.Department;
import com.lxyk.yygh.model.hosp.Hospital;
import com.lxyk.yygh.model.hosp.Schedule;
import com.lxyk.yygh.vo.hosp.BookingScheduleRuleVo;
import com.lxyk.yygh.vo.hosp.ScheduleOrderVo;
import com.lxyk.yygh.vo.hosp.ScheduleQueryVo;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;
    
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //上传排班
    @Override
    public void saveSchedule(Map<String, Object> paramMap) {

        //map转换为对象
        String mapString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(mapString, Schedule.class);
        System.out.println(schedule+"========================");
        //是否存在；
        Schedule targetSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        System.out.println(targetSchedule+"目标");
        HashOperations<String,String, String> hashOps = redisTemplate.opsForHash();
        if(targetSchedule!=null){

            if(schedule.getAmount()!=null){
                targetSchedule.setAmount(schedule.getAmount());
            }
            if(schedule.getAvailableNumber()!=null){
                targetSchedule.setAvailableNumber(schedule.getAvailableNumber());
            }
            if(schedule.getReservedNumber()!=null){
                targetSchedule.setReservedNumber(schedule.getReservedNumber());
            }
            //存在即更新
            targetSchedule.setUpdateTime(new Date());
            targetSchedule.setIsDeleted(0);
            targetSchedule.setStatus(1);
            scheduleRepository.save(targetSchedule);
//            更新redis的数据
            hashOps.put(targetSchedule.getId(),"available_number",String.valueOf(schedule.getAvailableNumber()));
            hashOps.put(targetSchedule.getId(),"reserved_number",String.valueOf(schedule.getReservedNumber()));

            String availableNumber = hashOps.get(targetSchedule.getId(), "available_number");
            String reservedNumber = hashOps.get(targetSchedule.getId(), "reserved_number");
            System.out.println("修改"+availableNumber+reservedNumber);

        }else{
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
//            保存到redis
            String scheduleKey = schedule.getId();
//            存储到hash 中
            hashOps.put(scheduleKey,"available_number",String.valueOf(schedule.getAvailableNumber()));
            hashOps.put(scheduleKey,"reserved_number",String.valueOf(schedule.getReservedNumber()));

            String availableNumber = hashOps.get(schedule.getId(), "available_number");
            String reservedNumber = hashOps.get(schedule.getId(), "reserved_number");
            System.out.println("新增"+availableNumber+reservedNumber);
        }

    }

    /**
     * 分页查询排班信息
     * @param page
     * @param limit
     * @param scheduleQueryVo
     * @return
     */
    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //1.创建pageable对象，设置当前页和每页记录数
        //0是第一页
        PageRequest pageable = PageRequest.of(page - 1, limit);
        //ScheduleQueryVo转换Schedule
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        //构建对象
        //改变默认字符串匹配方式:模糊查询 改变大小写忽略方式
        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //创建Example对象
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    /**
     * 删除排班
     * @param hoscode
     * @param hosScheduleId
     */
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        //根据医院编号和排班编号查询
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 查询排班规则数据
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
       //使用mongodbTemplate进行查询了
        ////1 根据医院编号 和 科室编号 查询
        Criteria criteria=Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        // aggregation  集合体
        Aggregation agg= Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                //默认分组会放在_id上
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //4 实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );

        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        log.info("********************bookingScheduleRuleVoList******************");
        log.info("bookingScheduleRuleVoList,{}",bookingScheduleRuleVoList);
        log.info("********************bookingScheduleRuleVoList******************");

        //分组查询的总记录数
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.match(criteria),Aggregation.group("workDate"));
        //执行
        AggregationResults<BookingScheduleRuleVo> scheduleRuleVos = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        int total=scheduleRuleVos.getMappedResults().size();

        //把日期对应星期获取
        for(BookingScheduleRuleVo bookingScheduleRuleVo:bookingScheduleRuleVoList){
            //周几根据workDate获取
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);
        return result;
    }


    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * 查询排班详细信息
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        Date toDate = new DateTime(workDate).toDate();
        ////根据参数查询mongodb
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, toDate);

        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });
        return scheduleList;
    }

//    获取排班可预约日期数据
    @Override
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {

        Map<String, Object> result = new HashMap<>();

        //根据hoscode查找医院，医院有预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        //根据医院编号得到预约规则
        if(null == hospital) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //=================预约规则==============================
        BookingRule bookingRule = hospital.getBookingRule();
        //获取可预约日期分页数据
        IPage ipage=this.getListDate(page,limit,bookingRule);
        //当前页可预约日期
        List<Date> dateList=ipage.getRecords();

        //获取可预约日期科室剩余预约数
        //Criteria n:标准
        //大概类似 hoscode=#{hoscode} and depcode=#{depcode} and workDate in #{workDate}
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        //Aggregation n 集合体,应该相当于wrppaer
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate") //别名
                        .count().as("docCount") //统计
                        .sum("availableNumber").as("availableNumber") //求和
                        .sum("reservedNumber").as("reservedNumber")
        );
        //调用mongodb的方法,Schedule.class   回来时  BookingScheduleRuleVo
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //获取科室剩余预约数，得到可预约的剩余数
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        System.out.println("=========scheduleVoList========");
        System.out.println("scheduleVoList"+scheduleVoList);
        System.out.println("=========scheduleVoList========");
        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date,BookingScheduleRuleVo> scheduleRuleVoMap=new HashMap<>();
        //不为空
        if(!CollectionUtils.isEmpty(scheduleVoList)){

            /**
             *   public static <T, K, U>
             *     Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
             *                                     Function<? super T, ? extends U> valueMapper) {
             *         return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
             *     }
             */
            //Collectors.tpMap() 转成map
            //设置key和value
            scheduleRuleVoMap=scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,BookingScheduleRuleVo->BookingScheduleRuleVo));
        }

        System.out.println("========= scheduleRuleVoMap========");
        System.out.println(" scheduleRuleVoMap"+ scheduleRuleVoMap);
        System.out.println("========= scheduleRuleVoMap========");

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=dateList.size(); i<len; i++) {
            //获取date
            Date date=dateList.get(i);
            //根据date key获取value
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);

            // 如果等于 null  说明当天没有排班医生  无号
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //设置可预约日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约 状态0：正常  1：即将放号   -1: 当天已停止挂号
            if(i==len-1&&page==ipage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else{
                bookingScheduleRuleVo.setStatus(0);
            }

            //当天预约如果过了停号时间，不能预约
            if(i==0&&page==1){
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()){
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }//for结束

        //可预约日期规则数据  最终放到map中
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", ipage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }
    

    /**
     * 获取可预约日期分页数据
     * //手动获取数据
     */
    private IPage getListDate(int page, int limit, BookingRule bookingRule) {
        //放号时间
        String release = bookingRule.getReleaseTime();
        //new Date()
        Date date = new Date();
        //获取当天放号时间   年 月 日 小时 分钟
        DateTime releaseTime = this.getDateTime(date, release);
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if(releaseTime.isBeforeNow())
            cycle+=1;

        //可预约所有日期，最后一天显示即将放号倒计时
        //从现在开始，往后cycle天
        ArrayList<Date> dateArrayList = new ArrayList<>();
        for(int i=1;i<cycle;i++){
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateArrayList.add(new DateTime(dateString).toDate());
        }

        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        ArrayList<Date> pageDateList = new ArrayList<>();
        int start=(page-1)*limit;
        int end =(page-1)*limit+limit;
        //如果可以显示数据小于7，直接显示
        if(end>dateArrayList.size()){
            end=dateArrayList.size();
        }

        for(int i=start;i<end;i++){
            pageDateList.add(dateArrayList.get(i));
        }
        //如果可以显示数据大于7
        //传入的page,limit
        IPage<Date> iPage= new com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date>(page,7,dateArrayList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     * @param date 当日日期
     * @param timeString  放号时间
     * @return
     */
    private DateTime getDateTime(Date date, String timeString){

        String dateTimeString=new DateTime(date).toString("yyyy-MM-dd")+" "+timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;

    }

    //根据scheduleId获取排班信息
    @Override
    public Schedule getScheduleById(String scheduleId) {

        Optional<Schedule> optional = scheduleRepository.findById(scheduleId);
        Schedule schedule = optional.get();
        return this.packageSchedule(schedule);
    }


    /**
     * //    根据排班id获取预约下单数据
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //先把schedule查询出来，得到hoscode
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        if(null == schedule) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //查找预约规则
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if(hospital==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        if(null == bookingRule) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //把获取的数据设置到 ScheduleOrderVo
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        //退号日期 date,前一天的退号时间之前才可以退号
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());

        //设置退号时间
        scheduleOrderVo.setQuitTime(quitTime.toDate());

//        @ApiModelProperty(value = "挂号开始时间")
//        private Date startTime;
//        @ApiModelProperty(value = "挂号结束时间")
//        private Date endTime;
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //预约截止时间
        DateTime endTime=this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(),bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    /**
     * 更新排班数据，用于mq
     * @param schedule
     */
    @Override
    public void update(Schedule schedule) {
        Date date = new Date();
        schedule.setUpdateTime(date);
        scheduleRepository.save(schedule);
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private Schedule packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }


}
